<template>
	<div class="app-container">
		<div class="search-container">
			<el-form ref="queryFormRef" :model="queryParams" :inline="true">
				<el-form-item prop="keywords" label="关键字">
					<el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable @keyup.enter="handleQuery"/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery">
						<i-ep-search/>
						搜索
					</el-button>
					<el-button @click="resetQuery">
						<i-ep-refresh/>
						重置
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		
		<el-card shadow="never">
			<template #header>
				<el-button type="success" @click="openDialog()">
					<i-ep-plus/>
					新增
				</el-button>
			</template>
			
			<el-table ref="dataTableRef" v-loading="loading" :data="tableList" highlight-current-row border
								@selection-change="handleSelectionChange">
				<el-table-column label="客户姓名" prop="customName" min-width="100"/>
				<el-table-column label="开始租赁日期" prop="startDt" min-width="100"/>
				<el-table-column label="结束租赁日期" prop="endDt" min-width="100"/>
				<el-table-column label="退租日期" prop="returnDt" width="150"/>
				<el-table-column label="支付金额" prop="payAmount" width="150">
				</el-table-column>
				<el-table-column label="退租金额" prop="returnAmount" width="150">
				</el-table-column>
				<el-table-column label="送货地址" prop="address" width="150">
				</el-table-column>
				<el-table-column label="当前状态" prop="status" width="150" >
					<template #default="scope">
						{{ scope.row.status == '10' ? "租赁中" :
						scope.row.status == '20' ? "已退租" : "" }}
					</template>
				</el-table-column>
				<el-table-column label="经销商" prop="dealerName" width="150"/>
				<el-table-column label="备注" prop="remark" width="150"/>
				<el-table-column fixed="right" label="操作" :width="mobile === 'mobile' ? 90 : 220">
					<template #default="scope">
						<el-button type="primary" size="small" link @click="openDialog(scope.row.id)">
							<i-ep-edit/>
							编辑
						</el-button>
						<el-button type="primary" size="small" link @click="handleDelete(scope.row.id)">
							<i-ep-delete/>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
									v-model:limit="queryParams.pageSize" @pagination="handleQuery"/>
		</el-card>
		
		<!-- 主管单位表单弹窗 -->
		<el-dialog v-model="dialog.visible" :title="dialog.title"
							 :width="screenWidth"
							 :fullscreen="mobile === 'mobile'"
							 class="system"
							 :style="{'--mobileAddFormHeight': mobile === 'mobile' ? (screenHeight - 117) + 'px' : 'auto'}"
							 close-icon="CloseBold"
							 draggable @close="closeDialog">
			<el-form ref="dialogFormRef" :model="formData" :rules="rules" label-width="100px">
				<el-form-item label="客户" prop="customId">
					<el-select :prefix-icon="Search" v-model="formData.customId" placeholder="请选择客户" @change="handleUserChange" clearable filterable>
						<template #prefix>
							<el-icon>
								<Search style="font-size: 25px" />
							</el-icon>
						</template>
						<el-option v-for="item in userSelects" :key="item.id" :label="item.name" :value="item.id"/>
					</el-select>
				</el-form-item>
				<el-form-item label="租赁周期" prop="dt">
					<el-date-picker
						v-model="formData.dt"
						type="daterange"
						range-separator="To"
						start-placeholder="开始租赁日期"
						end-placeholder="结束租赁日期"
						:size="'default'"
					/>
				</el-form-item>
				
				<el-form-item label="支付金额" prop="payAmount">
					<el-input-number v-model="formData.payAmount"
													 controls-position="right"
													 :min="0"
													 placeholder="请输入支付金额"/>
				</el-form-item>
				
				<el-form-item label="送货地址" prop="address">
					<el-input v-model="formData.address" placeholder="请输入送货地址"/>
				</el-form-item>
				
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注"/>
				</el-form-item>
			</el-form>
			
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	
	</div>
</template>

<script setup lang="ts">
import {computed} from "vue";
import {Search} from "@element-plus/icons-vue";

defineOptions({
	name: "dept",
	inheritAttrs: false,
});
import {
	QueryCustomList,
} from "@/api/agency/client";

import {
	QueryCustomLeaseList,
	addCustomLease,
	updateCustomLease,
	getCustomLeaseForm,
	deleteCustomLeases,
} from "@/api/agency/clientLease";

import {getDicts} from "@/store/modules/dict";

import {useScreen} from "@/store/modules/screen";

const screenStore = useScreen()
const mobile = computed(() => (screenStore.device));
const screenHeight = computed(() => (screenStore.screenHeight));
const screenWidth = ref(700)

function initScreen() {
	if (mobile.value === 'mobile') {
		screenWidth.value = screenStore.screenWidth;
	} else {
		screenWidth.value = 700;
	}
}

import { customLeaseListType, QueryForm, customLeaseFormType } from "@/api/agency/clientLease/types"

const queryFormRef = ref(ElForm);
const dialogFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<QueryForm>({
	pageNum: 1,
	pageSize: 10,
});

const tableList = ref<customLeaseListType[]>();

const dialog = reactive<DialogOption>({
	visible: false,
});

const formData = reactive<customLeaseFormType>({
	areaId: undefined,
	name: "",
});

const rules = reactive({
	dealerId: [{required: true, message: "请选择经销商", trigger: "blur"}],
	phone: [{required: true,trigger: "blur"},{
		pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
		message: "请输入正确的电话号码",
		trigger: "blur",
	}],
});


/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	QueryCustomLeaseList(queryParams)
		.then(({data}) => {
			tableList.value = data.list;
			total.value = data.total;
			loading.value = false;
		})
		.finally(() => {
		});
}

/**
 * 重置查询
 */
function resetQuery() {
	queryFormRef.value.resetFields();
	queryParams.pageNum = 1;
	queryParams.areaId = null;
	queryParams.level = null;
	handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.deptId);
}

function filterUser(val) {
	console.log("filterUser",userSelects.value)
	return userSelects.value.filter(item => item.id == val);
}

function handleUserChange(val) {
	console.log(val,filterUser(val)[0].name);
	formData.dealerName = filterUser(val)[0].dealerName;
	formData.customName = filterUser(val)[0].name;
	formData.dealerId = filterUser(val)[0].dealerId
}

const userSelects = ref([])

/**
 * 打开角色表单弹窗
 *
 * @param id
 */
function openDialog(id?: number) {
	dialog.visible = true;
	if (id) {
		dialog.title = "修改经销商信息";
		getCustomLeaseForm(id).then(({data}) => {
			Object.assign(formData, data);
			formData.dt = [formData.startDt, formData.endDt]
			formData.id = id;
		});
	} else {
		// formData.id = 0;
		dialog.title = "新增经销商信息";
	}
	QueryCustomList({pageNum: 1, pageSize: 9999}).then((data) => {
		if (data.success && data.data.list && data.data.list.length > 0) {
			userSelects.value = data.data.list;
		} else {
			userSelects.value = [];
		}
	})
}

const treeSelectRef = ref<any>();
//选择所属区域
const handelAreaChange = (val: any) => {
	// if(val.extend1==0){
	// 	formData.level=1;
	// }
	// else if(val.extend1==1){
	// 	formData.level=2;
	// }
	// else if(val.extend1==2){
	// 	formData.level=3;
	// }
	formData.areaName = val.label;
};

/**
 * 角色表单提交
 */
function handleSubmit() {
	dialogFormRef.value.validate((valid: any) => {
		if (valid) {
			loading.value = true;
			const id = formData.id;
			if(formData.dt && formData.dt.length > 0){
				formData.startDt = formData.dt[0];
				formData.endDt = formData.dt[1];
			}
			if (id) {
				updateCustomLease(id, formData)
					.then((resp) => {
						if (resp.success === true) {
							ElMessage.success(resp.msg);
							closeDialog();
							resetQuery();
						} else {
							ElMessage.warning(resp.msg);
						}
					})
			} else {
				addCustomLease(formData)
					.then((resp) => {
						if (resp.success === true) {
							ElMessage.success(resp.msg);
							closeDialog();
							resetQuery();
						} else {
							ElMessage.warning(resp.msg);
						}
					})
			}
		}
	});
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
	dialogFormRef.value.resetFields();
	dialogFormRef.value.clearValidate();
	
	formData.id = undefined;
	formData.address = '';
	formData.phone = '';
	formData.name = '';
	formData.areaId = '';
}

/**
 * 删除
 */
function handleDelete(DeptId?: number) {
	const DeptIds = [DeptId || ids.value].join(",");
	if (!DeptIds) {
		ElMessage.warning("请勾选删除项");
		return;
	}
	
	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		loading.value = true;
		deleteCustomLeases(DeptIds)
			.then((resp) => {
				if (resp.success === true) {
					ElMessage.success(resp.msg);
					resetQuery();
				} else {
					ElMessage.warning(resp.msg);
				}
			})
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消！'
		})
	});
}


onMounted(() => {
	initScreen()
	
	handleQuery();
});
// QueryCustomList({pageNum: 1, pageSize: 9999}).then((data) => {
// 	if(data.success && data.data.list && data.data.list.length > 0){
// 		userSelects.value = data.data.list;
// 	}else {
// 		userSelects.value = [];
// 	}
// })

// const areaOptions = getDicts("areaTrees").filter(item => item.value == '540000');
const areaOptions = getDicts("areaTrees");

</script>

<style lang="scss" scoped>
.el-form-item__label {
	width: 120px !important;
}

.el-select {
	width: 100% !important;
}
</style>
